const vm = new Vue({
    el: '#eformapp',
    data: {
        formJson: {"widgetList":[],"formConfig":{"labelWidth":80,"labelPosition":"left","size":"","labelAlign":"label-left-align","cssCode":"","customClass":"","functions":"","layoutType":"PC","onFormCreated":"","onFormMounted":"","onFormDataChange":"","onFormValidate":""}},
        formData: {},
        optionData: {},
        templateId: '',
        tempOneCode:'',
        dataLinkTable: '',
        dataId:'',
        iframeHeight:0,
        isSendMessage:false,
        // 显示默认的提交按钮
        showDefaultSubmitButton: true
    },
    watch: {
        iframeHeight(newVal, oldVal) {
            window.parent.postMessage(
                {
                    vueAppHeight:newVal
                },
                "*"
            );
            // window.parent.setContentHeight(newVal);
        },
    },
    //https://www.yuque.com/variantdev/vform/pi1mff#mE6tm
    mounted() {
        let that = this;
        this.iframeHeight = document.body.scrollHeight;
        console.log('newVal-->>' +   this.iframeHeight)
        setInterval(this.valChange, 200);
        // 初始化表单配置和数据
        this.templateId = T.p('templateId');
        this.tempOneCode = T.p('tempOneCode');
        this.dataId = T.p('dataId');
        if (this.dataId) {
            //从后端接口获取已保存的数据对象，并赋值给formData变量
            $.ajax({
                async: false,
                url: T.webRoot + '/eform/eformdata/info/' + this.dataId,
                type: 'GET',
                success: function(res) {
                    if (res.code === 0) {
                        let newFormData = $.parseJSON(res.data.dataJson);
                        $.ajax({
                            async: false,
                            url: T.webRoot + '/eform/eformtemplate/info/' + res.data.templateId,
                            type: 'GET',
                            success: function(res) {
                                let templateConfig = $.parseJSON(res.data.templateConfig);
                                that.templateId  = res.data.templateId;
                                that.$refs.vFormRef.setFormJson(templateConfig);
                                that.$nextTick(() => {
                                    that.$refs.vFormRef.setFormData(newFormData);
                                });
                            },
                            error: function(err) {
                                console.log('err', err)
                            }
                        });
                    } else {
                        console.log('加载数据失败！');
                    }
                },
                error: function(err) {
                    console.log('err', err)
                }
            });
        }else if ( this.templateId){
            $.ajax({
                async: false,
                url: T.webRoot + '/eform/eformtemplate/info/' + this.templateId,
                type: 'GET',
                success: function(res) {
                    let templateConfig = $.parseJSON(res.data.templateConfig);
                    that.$refs.vFormRef.setFormJson(templateConfig);
                    that.submitUrl = res.data.submitUrl;

                },
                error: function(err) {
                    console.log('err', err)
                }
            });

        }else if (this.tempOneCode){ //第一次访问或者没有数据
            $.ajax({
                async: false,
                url: T.webRoot + '/eform/eformtemplate/infoByOneCode/' + this.tempOneCode,
                type: 'GET',
                success: function(res) {
                    let templateConfig = $.parseJSON(res.data.templateConfig);
                    that.$refs.vFormRef.setFormJson(templateConfig);
                    that.submitUrl = res.data.submitUrl;
                    that.templateId  = res.data.templateId;
                    const initData = that.getCookie('initData')
                    debugger;
                    const initDataJson = JSON.parse(decodeURIComponent(initData))
                    that.$refs.vFormRef.setFormData(initDataJson);
                    //   that.formData = initDataJson;
                    // that.$refs.vFormRef.setFormJson(templateConfig);
                },
                error: function(err) {
                    console.log('err', err)
                }
            });
        }

    },
    methods: {
        valChange: function() {
            this.iframeHeight = document.body.scrollHeight;
        },

        getCookie: function(name) {
            var start = document.cookie.indexOf(name + "="); //得到cookie字符串中的名称
            var len = start + name.length + 1; //得到从起始位置到结束cookie位置的长度
            //如果起始没有值且name不存在于cookie字符串中，则返回null
            if ((!start) && (name != document.cookie.substring(0, name.length))) {
                return null;
            }
            if (start == -1) return null; //如果起始位置为-1也为null
            var end = document.cookie.indexOf(';', len); //获取cookie尾部位置
            if (end == -1) end = document.cookie.length; //计算cookie尾部长度
            return unescape(document.cookie.substring(len, end)); //获取cookie值
        },
        // 表单提交
        defaultSubmitForm: function() {
            let that = this;

            this.$refs.vFormRef.getFormData().then( function(formData) {
                // Form Validation OK
                console.log('submitForm1', JSON.stringify(formData));
                let data = {};
                console.log('this.templateId-->>' + that.templateId)
                if (that.templateId){
                    data = {
                        'templateId': that.templateId,
                        'dataLinkTable': that.dataLinkTable,
                        'dataJson': JSON.stringify(formData),
                    };
                    $.ajax({
                        url: T.webRoot + '/eform/eformdata/save',
                        type: 'post',
                        contentType: 'application/json',
                        data: JSON.stringify(data),
                        success: function(res) {

                                window.parent.postMessage(
                                    {
                                        resKeyId:res.keyId
                                    },
                                    "*"
                                );


                            layer.msg(res.msg, {icon: 6});
                           // window.close();
                        },
                        error: function(err) {
                            layer.msg('网络异常，请稍后重试！', {icon: 5});
                        }
                    });
                }else {
                    layer.msg('数据异常1111，请稍后重试！', {icon: 5});
                }


            }).catch( function(error) {
                // Form Validation Failed
                //  alert(error)
                //layer.alert(error);
                window.parent.postMessage(
                    {
                        vueError:error
                    },
                    "*"
                );
            })
        }
    }
});